from bbkb.KBQuery import *
from bbkb.initial_data_load import load_data_on_startup
from bbkb.KnowledgeBase import KnowledgeBase, Item
from bbkb.initial_data_load import _persist_kb

def secondaryAvg(player):
	""" secA = (TB-H+BB+SB-CS)/AB """
	tb = totalBases(player)
	h = player['b_h']
	bb = player['b_ibb']+player['b_bb']
	sb = player['b_sb']
	cs = player['b_cs']
	ab = player['b_ab']
	#print '%s-%s+%s+%s-%s / %s' % (tb, h, bb, sb, cs, ab)
	secAvg = float(((float(tb)-float(h)+float(bb)+float(sb)-float(cs))/(float(ab))))
	#print secAvg
	return secAvg
	
def runsCreated(player):
	""" ((h+bb)*tb)/(ab+bb) """
	tb = totalBases(player)
	h = player['b_h']
	bb = player['b_ibb']+player['b_bb']
	ab = player['b_ab']
	
	rc = ((float(h)+float(bb))*float(tb))/float(ab+bb)
	return float(rc)

def rawAvg(player):
	""" ((h+tb+1.5*(bb+hbp)+sb+sh+sf)/(ab+bb+hbp+sh+sf+cs+(sb/3)) """
	tb = totalBases(player)
	h = player['b_h']
	bb = player['b_bb']
	sb = player['b_sb']
	cs = player['b_cs']
	ab = player['b_ab']
	hbp = player['b_hbp']
	sh = player['b_sh']
	sf = player['b_sf']
	"""
	print h
	print tb
	print (1.5)*(bb+hbp)
	print sb
	print sh
	print sf
	print '-----------------------'
	print ab
	print bb
	print hbp
	print sh
	print sf
	print cs
	print float(sb/3)
	"""
	rawAvg = (h+tb+float(1.5*(bb+hbp))+sb+sh+sf)/(ab+bb+hbp+sh+sf+cs+float(sb/3))
	return float(rawAvg)
	
def totalBases(player):
	""" calculate total bases """

	doubles = player['b_2b']
	triples = player['b_3b']
	homeruns = player['b_hr']
	otherHits = doubles+triples+homeruns
	singles = int(player['b_h'])-otherHits

	return (singles+(doubles*2)+(triples*3)+(homeruns*4))

def listCoreData(playerCore):
	print "*** ",playerCore['namefirst'],playerCore['namelast'], " ***"
	print "Born: ",playerCore['birthcity'],playerCore['birthcountry']
	print "Month: ",playerCore['birthmonth'], " Year: ", playerCore['birthyear']
	print "Bats: ", playerCore['bats']
	print "Throws: ", playerCore['throws']


def listDerivedData(playerStats,resultsName):
	#print playerStats
	tb = totalBases(playerStats)
	print "Position: ", playerStats['f_pos']
	print '%s : %s'% (resultsName, playerStats[resultsName])
	print "-"*20
	print '-- AB: %s Hits: %s 2B: %s 3B: %s HR: %s RBI: %s Total Bases: %s' % (playerStats['b_ab'],
			playerStats['b_h'], playerStats['b_2b'], playerStats['b_3b'], playerStats['b_hr'],
			playerStats['b_rbi'],tb)
	avg = float(playerStats['b_h'])/float(playerStats['b_ab'])
	print '-- Average: {0:.3f}'.format(avg)
	secAvg = secondaryAvg(playerStats)
	print '-- Secondary Average: {0:.3f} '.format(secAvg)
	runsCr = runsCreated(playerStats)
	print '-- Runs Created: {0:0.0f}'.format(runsCr)
	ravg = rawAvg(playerStats)
	print '-- Raw Avg: {0:.3f}'.format(ravg)
	print "-"*20

	
def getInfoCounts(targetYear, criteriaList, resultsName):
	""" Method for getting count of an item in a list """
		
	""" Get Year """
	#targetYear = '2000'
	yearField= None
	yearLookups = kb.lookup_tables['year']
	for yearId in yearLookups:
		if yearLookups[yearId]['value'] == targetYear:
			print 'Found %s for %s' % (yearId, targetYear)
			yearField = '%s:%s' % ('year',yearId)
	
	
	""" Check algorithm sent in """
	
	listOfLists = []
	endSet = []
	""" Get attribute values """
	for entry in criteriaList:
		
		print 
		lookupTable = entry[0]
		operator = entry[1]
		matchValue = entry[2]
		
		lookupData = kb.lookup_tables[lookupTable]
		infoData = None
		infoDataset = []
		for target in lookupData:
			#print 'Checking target: ', target, ' for ', matchValue
			#print '*** Comparator: ', comparator
			if operator == '>':
				if lookupData[target]['value'] > int(matchValue):
					infoData = '%s:%s' % (lookupTable, target)
					infoDataset.append(infoData)
			if operator == '<':
				if lookupData[target]['value'] < int(matchValue):
					infoData = '%s:%s' % (lookupTable, target)
					infoDataset.append(infoData)
			if operator == '=':
				if lookupData[target]['value'] == matchValue:
					print "inhere", matchValue
					infoData = '%s:%s' % (lookupTable, target)
					infoDataset.append(infoData)
		
		print 'Found %d entries for %s' % (len(infoDataset), lookupTable)
	
		""" Build our search string """
		searchString = yearField+'~'+lookupTable
	
		entryList = kb._find(searchString)
		print "Found %d entries for search: %s" % (len(entryList), searchString)
	
		# we find our target attribute in the 2nd position (playerid=0, year=1)
		playerList = [player for player in entryList if player.split('~')[2] in infoDataset]

		pIDList = []
		for tmpPlayer in playerList:
			pIDList.append(tmpPlayer.split('~')[0])
		
		listOfLists.append(pIDList)
		
	endSet = set()

	j=0
	for pList in listOfLists:
		z1 = set(pList)
		if j == 0:
			endSet = z1
			j=j+1
		else:
			endSet = z1 & endSet
			
	""" add the attribute to the player for that year """
	if len(resultsName) > 0:
		for tmpPlayer in endSet:
			yearData = Item('year', targetYear)
			kb.add(tmpPlayer, yearData, Item(resultsName,'true'))

	print "-"*40
	print 'Number of players %d' % len(endSet)
	print "-"*40
	# return the set of player:id values
	return endSet
	

# Query handlers must be ordered from most specific
# to least specific
query_handlers = [ItemFilterQuery(), ItemQuery()]
     
load_data_on_startup(None)

moreData = True

print "*** Debug ***"
print kb.lookup_tables.keys()
print "**************"

criteriaList = []

"""
playerAttr = 'f_pos'
playerTargetData = 'RF'
comparator = '='
criteriaList.append([playerAttr, comparator, playerTargetData])

playerAttr = 'b_ab'
playerTargetData = '400'
comparator = '>'
criteriaList.append([playerAttr, comparator, playerTargetData])

playerAttr = 'b_hr'
playerTargetData = '20'
comparator = '>'
criteriaList.append([playerAttr, comparator, playerTargetData])

playerAttr = 'b_rbi'
playerTargetData = '100'
comparator = '>'
criteriaList.append([playerAttr, comparator, playerTargetData])

targetYear = '2000'

"""
targetYear = raw_input('Enter the Year for comparison:')
while moreData == True:
	playerAttr = raw_input('Enter the Player Attribute filter name(b_ab, f_pos) :')
	comparator = raw_input('Enter filter type: >,<,= :')
	playerTargetData = raw_input('Enter the filter value:')

	criteriaList.append([playerAttr, comparator, playerTargetData])
	
	moreChecks = raw_input('Additional filter values (y/n)?')
	if moreChecks == 'y':
		moreData = True
	else:
		moreData = False
		resultsName = ''
		namedFilter = raw_input('Define attribute based on results (y/n)?')
		if namedFilter == 'y':
			resultsName = raw_input('New attribute name:')

playerData = getInfoCounts(targetYear, criteriaList, resultsName)

print "--- Player Info ---"
for pj in playerData:
	p2 = kb.get(pj)
	pi = p2[targetYear]

	listCoreData(p2)
	listDerivedData(pi,resultsName)

# persist 
_persist_kb(kb)